<?php
/*
  Plugin Name: Test Function
  Plugin URI: http://www.zogodesigns.com
  Description: A brief description of the Plugin.
  Version: 0.0
  Author: Leon Rowland
  Author URI: http://www.zogodesigns.com

 */
/*
 * Create the Custom Post Types (CP's) and Custom Taxonomies (CT's)
 *
 */
add_action( 'init', 'create_taxonomies', 0 );
add_action('init', 'create_custompost');

function create_custompost()
{
 
  register_post_type('products', array(
    'labels' => array(
        'name' => _x('Products', 'post type general name'),
        'singular_name' => _x('Product', 'post type singular name'),
        'add_new' => _x('Add New', 'book'),
        'add_new_item' => __('Add New Product'),
        'edit_item' => __('Edit Product'),
        'new_item' => __('New Product'),
        'view_item' => __('View Product'),
        'search_items' => __('Search Products'),
        'not_found' =>  __('No products found'),
        'not_found_in_trash' => __('No products found in Trash'),
        'parent_item_colon' => '',
        'menu_name' => 'Products'),
    'public' => true,
    'publicly_queryable' => true,
    'show_ui' => true,
    'show_in_menu' => true,
    'query_var' => true,
    'rewrite' => true,
    'capability_type' => 'products',
    'capabilities' => array(
        'publish_posts' => 'publish_products',
        'edit_published_posts' => 'edit_published_products',
        'edit_posts' => 'edit_products',
        'edit_others_posts' => 'edit_others_products',
        'delete_posts' => 'delete_products',
        'delete_others_posts' => 'delete_others_products',
        'read_private_posts' => 'read_private_products',
        'edit_post' => 'edit_product',
        'delete_post' => 'delete_product',
        'read_post' => 'read_product',
       	 ),
    'map_meta_cap' => true,
    'has_archive' => true,
    'hierarchical' => false,
    'menu_position' => null,
    'supports' => array(
        'title',
        'editor',
        'thumbnail',
        )
    )
  );
  register_post_type('locationpt', array(
    'labels' => array(
        'name' => _x('Locations', 'post type general name'),
        'singular_name' => _x('Location', 'post type singular name'),
        'add_new' => _x('Add New', 'book'),
        'add_new_item' => __('Add New Location'),
        'edit_item' => __('Edit Location'),
        'new_item' => __('New Location'),
        'view_item' => __('View Location'),
        'search_items' => __('Search Location'),
        'not_found' =>  __('No Location found'),
        'not_found_in_trash' => __('No Location found in Trash'),
        'parent_item_colon' => '',
        'menu_name' => 'Location'),
    'public' => true,
    'publicly_queryable' => true,
    'show_ui' => true,
    'show_in_menu' => true,
    'query_var' => true,
    'rewrite' => true,
    'capability_type' => 'post',
    'has_archive' => true,
    'hierarchical' => false,
    'menu_position' => null,
    'supports' => array(
        'title',
        'editor',
        'thumbnail',
        )
    )
  );
  register_post_type('storept', array(
    'labels' => array(
        'name' => _x('Stores', 'post type general name'),
        'singular_name' => _x('Store', 'post type singular name'),
        'add_new' => _x('Add New', 'Store'),
        'add_new_item' => __('Add New Store'),
        'edit_item' => __('Edit Store'),
        'new_item' => __('New Store'),
        'view_item' => __('View Store'),
        'search_items' => __('Search Store'),
        'not_found' =>  __('No Store found'),
        'not_found_in_trash' => __('No Store found in Trash'),
        'parent_item_colon' => '',
        'menu_name' => 'Store'),
    'public' => true,
    'publicly_queryable' => true,
    'show_ui' => true,
    'show_in_menu' => true,
    'query_var' => true,
    'rewrite' => true,
    'capability_type' => 'post',
    'has_archive' => true,
    'hierarchical' => false,
    'menu_position' => null,
    'supports' => array(
        'title',
        'editor',
        'thumbnail',
        )
    )
  );
}

function create_taxonomies()
{
  
  register_taxonomy('storetax','products', array(
    'hierarchical' => false,
    'labels' => array(
        'name' => _x( 'Stores', 'taxonomy general name' ),
        'singular_name' => _x( 'Store', 'taxonomy singular name' ),
        'search_items' =>  __( 'Search Stores' ),
        'all_items' => __( 'All Stores' ),
        'parent_item' => __( 'Parent Store' ),
        'parent_item_colon' => __( 'Parent Store:' ),
        'edit_item' => __( 'Edit Store' ),
        'update_item' => __( 'Update Store' ),
        'add_new_item' => __( 'Add New Store' ),
        'new_item_name' => __( 'New Store Name' ),
        'menu_name' => __( 'Store' ),
        ),
    'show_ui' => true,
    'query_var' => true,
    'rewrite' => array(
        'slug' => 'store'),
  ));

  register_taxonomy('locationtax',array('products', 'store'),array(
    'hierarchical' => false,
    'labels' => array(
        'name' => _x( 'Locations', 'taxonomy general name' ),
        'singular_name' => _x( 'Location', 'taxonomy singular name' ),
        'search_items' =>  __( 'Search Locations' ),
        'popular_items' => __( 'Popular Locations' ),
        'all_items' => __( 'All Locations' ),
        'parent_item' => null,
        'parent_item_colon' => null,
        'edit_item' => __( 'Edit Location' ),
        'update_item' => __( 'Update Location' ),
        'add_new_item' => __( 'Add New Location' ),
        'new_item_name' => __( 'New Location Name' ),
        'separate_items_with_commas' => __( 'Separate Location with commas' ),
        'add_or_remove_items' => __( 'Add or remove Location' ),
        'choose_from_most_used' => __( 'Choose from the most used Locations' ),
        'menu_name' => __( 'Locations' )),
    'show_ui' => true,
    'query_var' => true,
    'rewrite' => array(
        'slug' => 'writer' ),
  ));
}

/*
 * Backend Alterations to Products CP
 */
function posts_for_current_author($query) {
	global $user_level;

	if($query->is_admin && $user_level < 5) {
		global $user_ID;
		$query->set('author',  $user_ID);
		unset($user_ID);
	}
	unset($user_level);

	return $query;
}
add_filter('pre_get_posts', 'posts_for_current_author');


/*
 * Backend Alterations to Author Page and Details
 */

add_action( 'show_user_profile', 'my_show_extra_profile_fields' );
add_action( 'edit_user_profile', 'my_show_extra_profile_fields' );

function my_show_extra_profile_fields( $user ) { ?>

	<h3>Store Information</h3>

	<table class="form-table">

		<tr>
			<th><label for="store">Store Name</label></th>

			<td>
				<input type="text" name="store" id="store" value="<?php echo esc_attr( get_the_author_meta( 'store', $user->ID ) ); ?>" class="regular-text" /><br />
				<span class="description">Please enter this clients store name.</span>
			</td>
		</tr>
                <tr>
			<th><label for="location">City</label></th>

			<td>
				<input type="text" name="location" id="location" value="<?php echo esc_attr( get_the_author_meta( 'location', $user->ID ) ); ?>" class="regular-text" /><br />
				<span class="description">Please enter this clients location.</span>
			</td>
		</tr>

	</table>
<?php }

add_action( 'personal_options_update', 'my_save_extra_profile_fields' );
add_action( 'edit_user_profile_update', 'my_save_extra_profile_fields' );

function my_save_extra_profile_fields( $user_id ) {

	if ( !current_user_can( 'edit_user', $user_id ) )
		return false;

	/* Copy and paste this line for additional fields. Make sure to change 'twitter' to the field ID. */
	update_usermeta( $user_id, 'store', $_POST['store'] );
        update_usermeta( $user_id, 'location', $_POST['location'] );
}

add_filter('user_contactmethods','hide_profile_fields',10,1);

function hide_profile_fields( $contactmethods ) {
unset($contactmethods['aim']);
unset($contactmethods['jabber']);
unset($contactmethods['yim']);
return $contactmethods;
}

/*
 * Meta Box
 */
add_action("admin_init", "add_meta_panels");
function add_meta_panels() {

    remove_meta_box('tagsdiv-locationtax', 'products', 'core');
    remove_meta_box('tagsdiv-storetax', 'products', 'core');
    add_meta_box("product_details", "Product Options", "product_options", "products", "side", "core");
    add_meta_box("stores_taxonomy", "Store Name", "stores_options", "products", "side", "core");
    add_meta_box("locations_taxonomy", "Location", "locations_options", "products", "side", "core");
}

//Function for callback from add_meta_box for product details
function product_options() {

    // Nonce creators for security
    wp_nonce_field(__FILE__, 'products_nonce');
    wp_create_nonce('products_nonce');

    //global post variable and retrieving meta data
    global $post;
    $custom = get_post_meta($post->ID, 'price', true);

    // Printing to front the entry field
    echo '<label for="price">';
    _e("Enter the current price", 'myplugin_textdomain');
    echo '</label> ';
    echo '<input type="text" id="price" name="price" value="' . $custom . '" size="15"/>';
}

//Function to update product details metabox and information.
function update_product_options($post_id) {

    // verify if this is an auto save routine.
    // If it is our form has not been submitted, so we dont want to do anything
    if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE)
        return $post_id;

    // Check permissions
//    if ('products' == $_POST['post_type']) {
//        if (!current_user_can('edit_products', $post_id))
//            return $post_id;
//    }

    // OK, we're authenticated: we need to find and save the data
    $mydata = $_POST['price'];

    // @todo ZOGO Add Security and nonces
    // Updates Price Metafield
    update_post_meta($post_id, "price", $mydata);

    return $mydata;
}

// Stores Meta Box controls and creation
function stores_options($post) {

    // Nonce creators for security
    wp_nonce_field(__FILE__, 'taxonomy_stores');
    wp_create_nonce('taxonomy_stores');

    // Get all store taxonomy terms
    $stores = get_terms('stores', 'hide_empty=0');
    // Get store taxonomy names
    $storenames = wp_get_object_terms($post->ID, 'stores');

    // Frontend prints
    echo "<select name='stores' id='stores'>";
    echo "<option class='theme-option' value=''";

    // If the current post has no assigned term then select none
    if (!count($storenames)) {
        echo " selected";
    } echo ">None</option>\n";

    // Foreach loop for all store taxonomy terms
    foreach ($stores as $store) {

        // If the current storenames var has a filled entry and assigns that the selected state
        if (!is_wp_error($storenames) && !empty($storenames) && !strcmp($store->slug, $storenames[0]->slug))
            echo "<option class='theme-option' value='" . $store->slug . "' selected>" . $store->name . "</option>\n";
        else
            echo "<option class='theme-option' value='" . $store->slug . "'>" . $store->name . "</option>\n";
    }

    // End the first echo with the closing statement
    echo "</select>\n";
}

// Stores Meta Box Save data and security checks
function update_stores_data($post_id) {

    if (!wp_verify_nonce($_POST['taxonomy_stores'], __FILE__)) {
        return $post_id;
    }

    // verify if this is an auto save routine. If it is our form has not been submitted, so we dont want to do anything
    if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE)
        return $post_id;


    // Check permissions
    if ('product' == $_POST['post_type']) {

        if (!current_user_can('edit_products', $post_id))
            return $post_id;
    }

    // OK, we're authenticated: we need to find and save the data
    $post = get_post($post_id);

    if ($post->post_type == 'products') {
        $stores = $_POST['stores'];
        wp_set_object_terms($post_id, $stores, 'stores');
    }
    return $stores;
}

// Locations Meta Box controls and creation
function locations_options($post) {

    global $current_user;
    //Nonce creators for security
    wp_nonce_field(__FILE__, 'taxonomy_location');
    wp_create_nonce('taxonomy_location');

    // Get all location taxonomy terms
    $locations = get_terms('locationtax', 'hide_empty=0');
    // Get store taxonomy names
    $locationsnames = wp_get_object_terms($post->ID, 'locationtax');
    $authorfield = get_the_author_meta( 'location', $current_user->ID );
    

// Frontend prints
    echo "<select name='locations' id='locations'>";
    echo "<option class='theme-option' value=''";

    // If the current post has no assigned term then select none
    if (!count($locationsnames)) {
        echo " selected ";
    } echo ">None</option>\n";

    
    foreach ($locations as $location){
        
        if($authorfield == $location->name) {
            echo "<option class='theme-option' value='" . $location->slug . "' selected>" . $location->name . "</option>\n";
        } else {
            echo "<option class='theme-option' value='" . $location->slug . "'>" . $location->name . "</option>\n";
        }
    }
    

    
//    // Foreach loop for all location taxonomy terms
//    foreach ($locations as $location) {
//
//        // If the current locationsnames var has a filled entry and assigns that the selected state
//        if (!is_wp_error($locationsnames) && !empty($locationsnames) && !strcmp($location->slug, $locationsnames[0]->slug))
//            echo "<option class='theme-option' value='" . $location->slug . "' selected>" . $location->name . "</option>\n";
//        else
//            if($location == $authorfield){
//
//            }
//
//
//
//    }

    // Ends the first echo with the closing statement
    echo "</select>\n";
}

// Locations Meta Box Save data and security checks
function update_locations_data($post_id) {

    if (!wp_verify_nonce($_POST['taxonomy_location'], __FILE__)) {
        return $post_id;
    }

    // verify if this is an auto save routine. If it is our form has not been submitted, so we dont want to do anything
    if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE)
        return $post_id;


    // Check permissions
    if ('product' == $_POST['post_type']) {

        if (!current_user_can('edit_products', $post_id))
            return $post_id;
    }

    // OK, we're authenticated: we need to find and save the data
    $post = get_post($post_id);

    if ($post->post_type == 'products') {
        $locationspost = $_POST['locations'];
        wp_set_object_terms($post_id, $locationspost, 'locationtax');
    }
    return $locations;
}